package com.example.springbootalipaydemo.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.example.springbootalipaydemo.config.AlipayTemplate;
import com.example.springbootalipaydemo.entity.Order;
import com.example.springbootalipaydemo.entity.PayAsyncVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chaird
 * @create 2023-06-04 11:47
 */
@RestController
public class OrderController {

  public Map<Long, Order> orderMap = new HashMap<>();


  @GetMapping("/addOrder")
  public Object addOrder() {
    Order mockOrder = new Order();
    mockOrder.setOrderId(System.currentTimeMillis());
    mockOrder.setOrderName("java书一本");
    mockOrder.setNumberId(95L);
    mockOrder.setTicketNum(1);
    mockOrder.setCost(10);
    mockOrder.setStatus("init");
    mockOrder.setPayType(null);
    mockOrder.setPayId(null);

    // 存db
    orderMap.put(mockOrder.getOrderId(), mockOrder);
    return mockOrder;
  }


    @Autowired
    private AlipayTemplate alipayTemplate;


  //http://localhost:8080/payOrder?orderId=1685860318875
  @GetMapping(value = "/payOrder",produces = "text/html")
  public Object payOrder(@RequestParam("orderId") Long orderId) throws AlipayApiException {
      Order order = orderMap.getOrDefault(orderId, buildOrder(orderId));
      String payUrl = alipayTemplate.pay(order);
      return payUrl;
  }

  @PostMapping(value = "/payOrderCallBack")
  public Object payOrderCallBack(PayAsyncVo asyncVo, HttpServletRequest request) throws AlipayApiException {
    // 只要收到支付宝的异步通知，返回 success 支付宝便不再通知
    // 获取支付宝POST过来反馈信息
    //TODO 需要验签
    Map<String, String> params = new HashMap<>();
    Map<String, String[]> requestParams = request.getParameterMap();
    for (String name : requestParams.keySet()) {
      String[] values = requestParams.get(name);
      String valueStr = "";
      for (int i = 0; i < values.length; i++) {
        valueStr = (i == values.length - 1) ? valueStr + values[i]
                : valueStr + values[i] + ",";
      }
      //乱码解决，这段代码在出现乱码时使用
      // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
      params.put(name, valueStr);
    }

    boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(),
            alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名

    if (signVerified) {
      System.out.println("签名验证成功...");

      System.out.println("报保存交易流水信息：" + JSONObject.toJSONString(asyncVo));

      //流水状态
      String trade_status = asyncVo.getTrade_status();
      //订单状态
      Long orderId = Long.valueOf(asyncVo.getOut_trade_no());

      Order order = orderMap.getOrDefault(orderId, buildOrder(orderId));
      order.setStatus(trade_status);
      //mock存db,//去修改订单状态
      orderMap.put(orderId, order);

      return "success";
    } else {
      System.out.println("签名验证失败...");
      return "error";
    }
  }

  //http://localhost:8080/queryAliPay?orderId=1685860318875
  @GetMapping(value = "/queryAliPay")
  public Object queryAliPay(@RequestParam("orderId") Long orderId) throws Exception{
    AlipayClient alipayClient = alipayTemplate.getClient();
    AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
    AlipayTradeQueryModel model = new AlipayTradeQueryModel();
    model.setOutTradeNo(orderId.toString());
    request.setBizModel(model);
    AlipayTradeQueryResponse response = alipayClient.execute(request);
    System.out.println(response.getBody());
    if (response.isSuccess()) {
      System.out.println("调用成功");
    } else {
      System.out.println("调用失败");
    }

    return response;
  }


  private Order buildOrder(Long orderId){
    Order mockOrder = new Order();
    mockOrder.setOrderId(orderId);
    mockOrder.setOrderName("java书一本");
    mockOrder.setNumberId(95L);
    mockOrder.setTicketNum(1);
    mockOrder.setCost(10);
    mockOrder.setStatus("init");
    mockOrder.setPayType(null);
    mockOrder.setPayId(null);
    return mockOrder;
  }
}
